import { aesMinEncrypt } from '../../utils/util'
const app = getApp()
let url =
  'https://xxcapp.xidian.edu.cn/uc/api/minigram/qy-auth?login_from=miniqyauth&access_token='
Page({
  data: {
    path: '',
  },
  onShow() {
    wx.$API['login/getServiceTime']().then((res) => {
      let { currentTime } = res
      let p = { timeMillis: currentTime }
      const request = {
        signature: aesMinEncrypt(JSON.stringify(p)),
      }
      wx.$API['login/getXadzToken'](request)
        .then((res) => {
          this.setData({
            path: url + res.data[0],
          })
        })
        .catch((error) => {
          console.log(error, 'error')
          wx.showToast({
            title: error,
            icon: 'none',
            duration: 2000,
          })
        })
    })
  },
  // 西安电子科技大学登录
  pagePostMessage: function (e) {
    let { number } = e.detail.data[0]
    wx.login({
      success: (codes) => {
        wx.showLoading({
          title: '正在登录...',
          mask: true,
        })
        wx.$API['login/getServiceTime']()
          .then((res) => {
            return new Promise((resolve, reject) => {
              let { currentTime } = res
              let schoolCode = 4161010701
              let param = {
                schoolCode,
                userId: number,
                timeMillis: currentTime,
              }
              let signature = JSON.stringify(param)
              const request = {
                schoolCode,
                loginType: 6, // 登录类型
                code: codes.code,
                signature: aesMinEncrypt(signature),
              }
              wx.$API['login/login'](request)
                .then((res) => {
                  wx.hideLoading()
                  app.globalData.from = 'end'
                  this.afterLogin(res)
                })
                .catch((error) => reject(error))
            })
          })
          .catch((error) => {
            wx.hideLoading()
            console.log(error, 'error')
            wx.showModal({
              title: '提示',
              content: `接口错误 ${error}. 点击重新验证登录`,
              showCancel: false,
            }).then((res) => {
              // wx.navigateTo({
              //   url: '/pages/xAdzkjdx/index',
              // })
            })
          })
      },
      fail: (err) => {
        wx.showModal({
          title: '提示',
          content: '获取code失败,请退出微信后重试',
          showCancel: false,
        })
      },
    })
  },
  /**
   * @see 登录后对返回值统一处理
   */
  afterLogin(result) {
    const { token, data, schoolConfig, code } = result
    app.storageData(token, data[0], schoolConfig, code)
    // 重定向地址
    const redirect = app.globalData.redirect
    app.globalData.redirect = ''
    if (redirect) {
      wx.redirectTo({
        url: redirect,
      })
    } else {
      wx.reLaunch({
        url: '/pages/home/index',
      })
    }
  },
})
